<template>
  <div>
    <!-- 搜索条件 -->
    <el-card v-show="showQueryForm" class="form-card">
      <QueryForm ref="queryFormRef" :form-data="queryFormData" :items="queryFormItems" :model="queryFormData" :show-control="true" label-width="100px">
        <QueryFormItem label="所属商务/代理">
          <el-select v-model="queryFormData.mid" placeholder="请选择" filterable>
            <el-option v-for="item in chainList" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </QueryFormItem>

        <template #control>
          <el-button icon="RefreshRight" type="primary" plain round @click="handleResetQueryForm">{{ $t('form.reset') }}</el-button>
          <el-button icon="Search" type="primary" round @click="handleSearch">{{ $t('form.search') }}</el-button>

        </template>
      </QueryForm>
    </el-card>
    <el-row  :gutter="8" class="introduce">
<!--      <el-col v-bind="attarSpan">-->
<!--        <div class="statis_item">-->
<!--          <div class="statis_item_left"><img src="../../../assets/images/alipay.png"/></div>-->
<!--          <div class="statis_item_right">-->
<!--            <div class="statis_item_title">年度目标：</div>-->
<!--            <div class="statis_item_content">新增100入网客户</div>-->
<!--          </div>-->
<!--        </div>-->
<!--      </el-col>-->
      <el-col v-bind="attarSpan">
        <div class="statis_item">
          <div class="statis_item_left"><img src="../../../assets/images/icon1.png"/></div>
          <div class="statis_item_right">
            <div class="statis_item_title">本月新增客户数：</div>
            <div class="statis_item_content">{{dataListKh.month}}
<!--             v-if="flag === 'up'"v-else-if="flag === 'down'" -->
              <SvgIcon v-if="parseFloat(dataListKh.ratio) <= 0 "  class="trend-icon" color="#F5222D" icon="ep:caret-bottom"/>
              <SvgIcon v-else class="trend-icon" color="#54FF00" icon="ep:caret-top"/>
              <text     :style="{
        color: parseFloat(dataListKh.ratio) <= 0 ? 'red' : '#54FF00',
        fontSize: '14px',
        fontWeight: '400'
    }">{{ dataListKh.ratio?dataListKh.ratio.replace(/^-/, ''):0  }}</text>
            </div>
          </div>
        </div>
      </el-col>
      <el-col v-bind="attarSpan">
        <div class="statis_item">
          <div class="statis_item_left"><img src="../../../assets/images/icon2.png"/></div>
          <div class="statis_item_right">
            <div class="statis_item_title">今日新增客户数：</div>
            <div class="statis_item_content">{{dataListKh.today}}
              <!--             v-if="flag === 'up'"v-else-if="flag === 'down'" -->
              <SvgIcon v-if="parseFloat(dataListKh.ratio) <= 0 "  class="trend-icon" color="#F5222D" icon="ep:caret-bottom"/>
              <SvgIcon v-else class="trend-icon" color="#54FF00" icon="ep:caret-top"/>
              <text     :style="{
        color: parseFloat(dataListKh.ratio) <= 0 ? 'red' : '#54FF00',
        fontSize: '14px',
        fontWeight: '400'
    }">{{ dataListKh.ratio?dataListKh.ratio.replace(/^-/, ''):0  }}</text>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>
    <!-- 列表数据 -->
    <el-card class="content-card">
      <!-- 工具栏 -->
      <table-toolbar v-model:columns="columns"
                     v-model:show-query-form="showQueryForm"
                     v-model:size="size"
                     v-model:stripe="stripe"
                     @refresh="handleSearch">
        <!-- 操作区域 -->
<!--        <el-button v-permission="'store:info:create'" icon="Plus" round type="primary" @click="handleFormShow(1)">新增商户</el-button>-->
      </table-toolbar>

      <!-- 列表记录 -->
      <div class="table-wrapper">
        <!-- 列表数据 -->
        <el-table ref="tableRef"
                  v-loading="loading"
                  :data="tableData"
                  :size="size"
                  :stripe="stripe"
                  row-key="id"
                  show-overflow-tooltip
                  @select="handleSelectChange"
                  @select-all="handleSelectAll"
                  @sort-change="handleSortChange">
          <template #empty>
            <el-empty class="table-empty" description="暂无数据"/>
          </template>

          <table-column :columns="columns">
            <template #full_name="scope">
              <div>{{ scope.row.full_name}}</div>
              <div>{{  scope.row.code }}</div>
            </template>

            <template #status="scope">
              <DictTag v-model="scope.row.status" :circle="false" dict-type="manager_status"/>
            </template>

<!--            <template #entry_status="scope">-->
<!--              <DictTag v-model="scope.row.entry_status" :circle="false" dict-type="shop_entry_status"/>-->
<!--            </template>-->

            <template #entry="scope">
              <DictTag v-model="scope.row.entry" :circle="false" dict-type="entry_status"/>
            </template>

            <template #public_queue_type="scope">
              <DictTag v-model="scope.row.public_queue_type" :circle="false" dict-type="public_queue_type"/>
            </template>

            <template #recommend="scope">
              <DictTag v-model="scope.row.recommend" :circle="false" dict-type="sys_yes_no" @click="handleSwitchRecommend(scope.row)"/>
            </template>

            <template #cover_url="scope">
              <el-popover v-if="isImageUrl(scope.row.cover_url)" placement="left" style="text-align: center;" trigger="hover" width="">
                <template #reference>
                  <img :alt="scope.row.cover_url" :src="scope.row.cover_url" style="height: 21px;max-width: 130px;">
                </template>
                <img :src="scope.row.cover_url" style="max-width: 220px;">
              </el-popover>
              <span v-else>-</span>
            </template>

            <template #operations="scope">
              <el-space :size="1" :spacer="spacer">
<!--                <el-button v-permission="'store:info:entry'" link type="primary" @click="handleFormEntry(scope.row)"></el-button>-->
<!--                <el-button v-permission="'store:info:update'" link type="primary" @click="handleFormShow(2, scope.row)">编辑</el-button>-->
<!--                <el-button v-permission="'store:info:delete'"  type="danger" link @click="handleDelete(scope.row)">删除</el-button>-->
              </el-space>
            </template>
          </table-column>
        </el-table>
        <!-- 分页操作 -->
        <el-pagination v-if="totalCount > 0"
                       :current-page="pageQuery.pageNum"
                       :page-size="pageQuery.pageSize"
                       :page-sizes="pageSizes"
                       :total="totalCount"
                       background
                       class="table-pagination"
                       layout="total, sizes, prev, pager, next"
                       @size-change="handleSizeChange"
                       @current-change="handleCurrentChange"/>
      </div>
    </el-card>

    <!-- 弹窗操作 -->
    <ShopForm ref="formRef" @refresh="handleSearch"/>
  </div>
</template>

<script lang="tsx" setup>
import { computed, h, onActivated, onBeforeMount, reactive, ref } from 'vue';
import { QueryForm, QueryFormItem } from '@/components/query-form';
import useLoading from '@/hooks/use-loading';
import TableColumn, { TableColumnData } from '@/components/table-column/index.vue';
import TableToolbar from '@/components/table-toolbar/index.vue';
import useTableSelection from '@/hooks/use-table-selection';
import {ElDivider, ElLoading, ElMessage, ElMessageBox, ElNotification, TableInstance} from 'element-plus';
import useTable from '@/hooks/use-table.ts';
import { hasPermission } from '@/utils/permission.ts';
import { computedOperateWidth, pickerShortcuts, toPercent } from '@/utils';
import { QueryFormItemRule } from '@/components/query-form/constants.ts';
import ShopForm from '@/views/shop/shop/shop-form.vue';
import { isImageUrl } from '@/utils/is.ts';
import { DictTag } from '@/components/dict-tag';
import { useRouter } from 'vue-router';
import {merchantDelete, merchantList, storeUpdateRecommend} from '@/api/api-store.ts';
import { UserInfoLink } from '@/components/user-info-link';
import {timeStamp} from "@/utils/validate.ts";
import {MANAGERList} from "@/api/api-manager.ts";
import Trend from "@/components/trend/index.vue";
import {SvgIcon} from "@/components/icon";
import {consoleHeader} from "@/api/dashboard.ts";
const spacer = h(ElDivider, { direction: 'vertical' })
defineOptions({name: 'store-list'});
const attarSpan = {
  xs: 24,
  sm: 12,
  md: 12,
  lg: 12,
  xl: 8,
};
// 查询
const queryFormData = reactive({
  status: undefined,
  mid:undefined
});
const chainList=ref<array>([])
const chainListOption=()=>{
  MANAGERList({page:1,size:9999,action:'list'}).then(res=>{
    chainList.value=res.body.list
  })
}
const queryFormRef = ref<InstanceType<typeof QueryForm>>();
const queryFormItems = ref<QueryFormItemRule[]>([
  {type: 'input', prop: 'id', label: '商户编号', placeholder: '请输入商户编号', clearable: true},
  {type: 'input', prop: 'name', label: '商户名称', placeholder: '请输入商户名称', clearable: true,},
  // {type: 'dict-select', prop: 'status', label: '所属商务/代理', placeholder: '请选择', dictType: 'manages_option', clearable: true,},
  {type: 'dict-select', prop: 'status', label: '进件状态', placeholder: '请选择', dictType: 'sys_yes_no', clearable: true,},
]);

// 列表数据
const tableRef = ref<TableInstance>();
const tableData = ref<any[]>([]);
const totalCount = ref(0);
const pickerDate = ref([]);

// 操作区域宽度计算
const operateWidth = computed(() => {
  let count = 0
  if (hasPermission('store:info:entry')) count += 1
  if (hasPermission('store:info:update')) count += 1
  if (hasPermission('store:info:delete')) count += 1
  return computedOperateWidth(count);
});

// 列设置
const columns = ref<TableColumnData[]>([
  // {prop: 'account', label: '登录账号', width: 105, align: 'center'},
  {prop: 'full_name', label: '商户名称', minWidth: 130, align: 'center'},
  {prop: 'product', label: '通道&费率', minWidth: 120, align: 'center', render: (scope, val) => <span>{val || '-'}</span>},
  {prop: 'manager', label: '所属商务/代理', minWidth: 120, align: 'center', render: (scope, val) => <span>{val.name || '-'}</span>},
  {prop: 'merchant_account', label: '总金额', minWidth: 130, align: 'center',render: (scope, val) => <span>{val.total_amount || '-'}</span>},
  {prop: 'merchant_account', label: '成功金额', minWidth: 130, align: 'center',render: (scope, val) => <span>{val.success_amount || '-'}</span>},
  {prop: 'merchant_account', label: '失败金额', minWidth: 130, align: 'center',render: (scope, val) => <span>{val.fail_amount || '-'}</span>},
  {prop: 'merchant_account', label: '退款金额', minWidth: 130, align: 'center',render: (scope, val) => <span>{val.refund_amount || '-'}</span>},
  {prop: 'merchant_account', label: '总手续费', minWidth: 130, align: 'center',render: (scope, val) => <span>{val.charge_amount || '-'}</span>},
  {prop: 'create_time', label: '入网时间', minWidth: 140, align: 'center',render: (scope, val) => <span>{timeStamp(val) || '-'}</span>},
  {prop: 'entry', label: '是否已进件', width: 100, align: 'center'},
  {prop: 'status', label: '状态', width: 120, align: 'center'},
]);

onBeforeMount(() => {
  if (operateWidth.value > 0) {
    columns.value.push({prop: 'operations', label: '操作', fixed: 'right', width: operateWidth.value, align: 'left', headerAlign: 'center'},)
  }
});

onActivated(() => {
  chainListOption()
  if (history.state.params && parseInt(history.state.params.refresh || '0') > 0) {
    handleSearch();
  }
});

const [loading, setLoading] = useLoading(false);
const {tableMethods, tableState} = useTable(() => fetchDataList(), queryFormRef, true, true);
const {size, stripe, showQueryForm, pageQuery, pageSizes} = tableState;
const {handleSizeChange, handleCurrentChange, handleSortChange, handleResetForm} = tableMethods;
const {handleSelectChange, handleSelectAll, multipleSelection, clearSelection} = useTableSelection(tableData, tableRef);
const dataListKh=ref({})
// 数据查询
const fetchDataList = async () => {
  setLoading(true);
  try {
    // 时间范围参数
    // @ts-ignore
    // queryFormData.date = pickerDate.value && pickerDate.value.length == 2 ? pickerDate.value[0] + '~' + pickerDate.value[1] : undefined
    // 查询数据
    const {body} = await merchantList({
      action:'list',
      page: pageQuery.pageNum,
      size: pageQuery.pageSize,
      ...queryFormData,
    });
    // 结果转换
    tableData.value = body.list;
    totalCount.value = body.pages.count;
  } catch (err) {
  } finally {
    setLoading(false);
  }
  try {
    dataListKh.value={}
    const {body} = await consoleHeader({action:'info',mode:"merchant"});
    dataListKh.value=body
  } catch (err) {
  } finally {
    setLoading(false);
  }
};

// 刷新数据
const handleSearch = () => {
  fetchDataList();
};

// 重置查询条件
const handleResetQueryForm = () => {
  pickerDate.value = [];
  queryFormData.mid=undefined
  clearSelection();
  handleResetForm();
};

/** 添加/修改操作 */
const router = useRouter();
const handleFormShow = (mode: number, row?: any) => {
  // 状态 0:草稿 10:审核中 20:审核失败 30:进件中 40:进件失败 100:已通过 110:已禁用
  let itemId = row ? row.id : 0
  if (mode === 0) { // 查看
    router.push({path: '/store/info/' + itemId})
  } else if (mode === 1) { // 新增
    router.push({path: '/store/create/' + itemId})
  } else if (mode === 2) { // 编辑
    router.push({path: '/store/update/' + itemId})
  } else if (mode === 3) { // 审核
    router.push({path: '/store/audit/' + itemId})
  }
};
//发起进件
const handleFormEntry = (row: any) => {
  router.push({path: '/store/entry/' + row.id,query:{id:0,mode:'add'}})
}
// 删除
const handleDelete=(row:any)=>{
  ElMessageBox.confirm(
    '是否确定删除此商户?',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(({value}) => {
    const loading = ElLoading.service({
      lock: true,
      text: '正在提交中...',
      background: 'rgba(0, 0, 0, 0.2)'
    })
    let params = {id: row.id,action:'delete'};
    // 提交数据
    merchantDelete(params).then(response => {
      // 提示信息
      ElNotification({title: '成功', message: '操作完成', type: 'success', duration: 2000})
      // 刷新数据
      handleSearch();
    }).finally(() => loading.close())
  }).catch(() => {

  });
}

/** 推荐状态切换 */
const handleSwitchRecommend = (row: any) => {
  if (row == null || row.id <= 0) return
  if (!hasPermission('store:info:update')) return

  ElMessageBox.prompt(h('p', null, [
    '您确定将店铺 ',
    h('span', {style: 'font-weight: bold;'}, row.name),
    ` 修改 `,
    h('span', {style: 'font-weight: bold;'}, '推荐'),
    ` 操作吗 ？`,
    <br/>, '排序值越大越靠前 (0=取消推荐)'
  ]), '提示', {
    type: 'warning',
    closeOnClickModal: false,
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputPlaceholder: '请输入排序值',
    inputPattern: /^[0-9]*$/,
  }).then(({value}) => {
    let newValue = parseInt(value) || 0
    if (newValue < 0) {
      ElMessage.error('请输入排序值');
      return
    }
    const loading = ElLoading.service({
      lock: true,
      text: '正在提交中...',
      background: 'rgba(0, 0, 0, 0.2)'
    });
    storeUpdateRecommend({id: row.id, order_num: newValue}).then(response => {
      // 提示信息
      ElNotification({title: '成功', message: '操作完成', type: 'success', duration: 2000})
      // 刷新列表数据
      handleSearch();
    }).finally(() => loading.close())
  }).catch(() => {

  });
};
</script>

<style lang="scss" scoped>
.introduce {
  > .el-col {
    margin-bottom: 8px;
  }

  .assimilate {
    .ratio {
      margin-left: 5px;
    }
  }

  .progress {
    width: 100%;

    :deep(.el-progress__text) {
      font-size: 14px !important;
    }
  }
  .introduce_item{
    //width: 288px;
    //height: 180px;
    background: linear-gradient( 135deg, #49A3FF 0%, #418DFB 100%);
    border-radius: 2px;
    //

    color: #fff;
  }
  .introduce_item_top{
    display: flex;
    padding: 14px 20px 0 20px;
    box-sizing: border-box;
    justify-content: space-between;
    font-family: PingFangSC, PingFang SC;
    font-weight: 400;
    font-size: 14px;
    line-height: 22px;
    font-style: normal;
    position: relative;
  }
  .introduce_item_progress{
    position: absolute;
    top: 10px;
    right: 20px;
  }
  .percentage-value{
    color: #fff;
    font-size: 14px;
  }
  .introduce_item_price{
    padding: 0 20px;
    box-sizing: border-box;
    font-family: PingFangSC, PingFang SC;
    font-weight: 500;
    font-size: 28px;
    margin: 6px 0;
    line-height: 38px;
    font-style: normal;
  }
  .introduce_item_center{
    padding: 0 20px;
    box-sizing: border-box;
    display: flex;
    justify-content: space-between;
    font-family: PingFangSC, PingFang SC;
    font-weight: 400;
    font-size: 14px;
    color: rgba(255,255,255,0.85);
    line-height: 22px;
    text-align: left;
    font-style: normal;
    margin-bottom: 16px;
  }
  .introduce_item_bom{
    //width: 288px;
    height: 66px;
    background: #296BF3;
    border-radius: 0px 0px 2px 2px;
    opacity: 0.7;
    padding: 14px 20px;
    box-sizing: border-box;
    .introduce_item_bom_item{
      font-family: PingFangSC, PingFang SC;
      font-weight: 400;
      font-size: 12px;
      color: rgba(255,255,255,0.85);
      line-height: 22px;
      text-align: left;
      font-style: normal;
    }
  }
}
.statis_item{
  background: #fff;
  border-radius: 2px;
  display: flex;
  //align-items: center;
  padding: 30px 23px;
  .statis_item_left{
    img{
      width: 62px;
    }
  }
  .statis_item_right{
    margin-left: 23px;
    .statis_item_title{
      font-weight: 400;
      font-size: 14px;
      color: rgba(0,0,0,0.85);
      line-height: 22px;
      text-align: left;
      font-style: normal;
      margin-bottom: 12px;
    }
    .statis_item_content{
      font-weight: 500;
      font-size: 24px;
      color: rgba(0,0,0,0.85);
      //line-height: 22px;
      text-align: left;
      font-style: normal;
      display: flex;
      align-items: center;
    }
  }
}
</style>
